package handler

import (
	"batch_flyway/internal/config"
	"batch_flyway/internal/db"
	"html/template"
	"net/http"
	"sync"
)

func QueryData(dsnstrList []config.Database) ([]db.QueryResult, error) {
	var wg sync.WaitGroup
	results := make([]db.QueryResult, len(dsnstrList))
	errChan := make(chan error, len(dsnstrList))

	for i, dsnstr := range dsnstrList {
		wg.Add(1)
		go func(i int, dsn string, row string, tablename string) {
			defer wg.Done()

			result, err := db.QueryDB(dsn, row, tablename)
			if err != nil {
				errChan <- err
				return
			}
			results[i] = result
			errChan <- nil
		}(i, dsnstr.GetDSN(), dsnstr.GetRow(), dsnstr.GetTableName())
	}

	wg.Wait()
	close(errChan)

	for err := range errChan {
		if err != nil {
			return nil, err
		}
	}

	return results, nil
}

func RenderTemplate(w http.ResponseWriter, results []db.QueryResult) {
	tmpl := template.Must(template.ParseFiles("internal/template/result.html"))
	tmpl.Execute(w, results)
}
